import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/a.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/utils/input_formatter_tools.dart';
import 'package:finance_app/src/widgets/form/form_edit_status_inherited_widget.dart';
import 'package:finance_app/src/widgets/wrapper/normal_form_wrapper.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/flutter_svg.dart';

/// [disableHideButton] 如果为true ，不可用状态下，button将会被隐藏
/// [canZero] 如果为true ,可以为0
class NumberForm extends StatefulWidget {
  final String title;
  final Widget titleWidget;
  final List<InlineSpan> titleSpan;
  final ValueChanged<int> onNumberCallback;
  final int initialNumber;
  final bool hasBottomBorder;
  final bool canZero;
  final bool disableHideButton;
  final bool canNavigate;
  final double inputWidth;

  const NumberForm(
      {Key key,
      this.title,
      this.canNavigate,
      this.disableHideButton = false,
      this.canZero,
      this.hasBottomBorder,
      this.onNumberCallback,
      this.initialNumber,
      this.titleSpan,
      this.inputWidth,
      this.titleWidget})
      : super(key: key);

  @override
  _NumberFormState createState() => _NumberFormState();
}

class _NumberFormState extends State<NumberForm> with KeepAliveMixin {
  TextEditingController controller = TextEditingController();
  FocusNode focusNode = FocusNode();

  void _onReduce() {
    int integer = int.parse(controller.text, onError: (e) => 0);
    integer--;
    setTextControllerValue(integer);
  }

  void _onAdd() {
    int integer = int.parse(controller.text, onError: (e) => 0);
    integer++;
    setTextControllerValue(integer);
  }

  void setTextControllerValue(int value) {
    String string = value.toString();
    controller.value = TextEditingValue(
      text: string,
      selection: TextSelection.collapsed(offset: string.length),
    );
  }

  @override
  void initState() {
    super.initState();
    if (widget.canZero == true) {
      controller.text = '0';
    }
    if (widget.initialNumber != null) {
      controller = TextEditingController(text: widget.initialNumber.toString());
    }
    controller.addListener(() {
      int integer = int.parse(controller.text, onError: (e) => 0);
      if (widget.canNavigate == true) {
        widget.onNumberCallback?.call(integer);
      } else {
        {
          widget.onNumberCallback?.call(integer);
        }
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    controller.dispose();
  }

  @override
  void didUpdateWidget(covariant NumberForm oldWidget) {
    if (oldWidget.initialNumber != widget.initialNumber) {
      controller.text = widget.initialNumber.toString();
    } else if (1 == 0) {
      super.didUpdateWidget(oldWidget);
    }
  }

  @override
  Widget build(BuildContext context) {
    return NormalFormWrapper(
      topPadding: getDp(12),
      bottomPadding: getDp(12),
      hasBottomBorder: widget.hasBottomBorder,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          if (widget.titleWidget != null)
            widget.titleWidget
          else if (widget.titleSpan != null)
            Text.rich(
              TextSpan(
                  children: widget.titleSpan,
                  style: TextStyle(
                    color: FormEditStatusInheritedWidget.ofEnable(context)
                        ? aceBlueColor
                        : aceBlackColor,
                    fontSize: getSp(16),
                    fontWeight: FontWeight.w700,
                    height: 16 / 14,
                  )),
            )
          else
            Text(
              widget.title,
              style: TextStyle(
                color: FormEditStatusInheritedWidget.ofEnable(context)
                    ? aceBlueColor
                    : aceBlackColor,
                fontSize: getSp(16),
                fontWeight: FontWeight.w700,
                height: 16 / 14,
              ),
            ),
          _buildNumberInput(context),
        ],
      ),
    );
  }

  Widget _buildNumberInput(BuildContext context) => Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          if (widget.disableHideButton == true &&
              !FormEditStatusInheritedWidget.ofEnable(context))
            Container()
          else
            ValueListenableBuilder<TextEditingValue>(
                valueListenable: controller, builder: _buildReduceWidget),
          SizedBox(
            width: widget.inputWidth ?? getDp(66),
            child: TextFormField(
              inputFormatters: [
                if (widget.canNavigate == true)
                  percentInputFormatter3
                else
                  intInputFormatter,
              ],
              keyboardType: TextInputType.numberWithOptions(decimal: true),
              focusNode: focusNode,
              scrollPadding: EdgeInsets.zero,
              decoration: InputDecoration(
                border: InputBorder.none,
                enabledBorder: InputBorder.none,
                hintText: '0',
              ),
              enabled: FormEditStatusInheritedWidget.ofEnable(context),
              controller: controller,
              style: TextStyle(
                color: FormEditStatusInheritedWidget.ofEnable(context)
                    ? aceBlueColor
                    : aceBlackColor,
                fontSize: getSp(16),
                fontWeight: FontWeight.w700,
              ),
              textAlign: TextAlign.center,
            ),
          ),
          if (widget.disableHideButton == true &&
              !FormEditStatusInheritedWidget.ofEnable(context))
            Container()
          else
            PressedOpacityButton(
              onPressed: FormEditStatusInheritedWidget.ofEnable(context)
                  ? _onAdd
                  : () {},
              child: SvgPicture.asset(
                A.assetsImagesStylePlus,
                width: getDp(20),
                height: getDp(20),
                color: FormEditStatusInheritedWidget.ofEnable(context)
                    ? null
                    : aceGrayColor,
              ),
            ),
        ],
      );

  Widget _buildReduceWidget(
      BuildContext context, TextEditingValue value, Widget child) {
    return PressedOpacityButton(
      onPressed: (FormEditStatusInheritedWidget.ofEnable(context) &&
                  (value.text == '0' ||
                      value.text == '' ||
                      value.text == null)) &&
              widget.canNavigate != true
          ? null
          : _onReduce,
      child: SvgPicture.asset(
        A.assetsImagesStyleMinus,
        width: getDp(20),
        height: getDp(20),
        color: FormEditStatusInheritedWidget.ofEnable(context)
            ? ((value.text == null || value.text == '' || value.text == '0') &&
                    widget.canNavigate != true
                ? aceGrayColor
                : null)
            : aceGrayColor,
      ),
    );
  }
}
